package com.qcu.controller.user;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qcu.annotation.LimitRate;
import com.qcu.annotation.RequireAuthorization;
import com.qcu.entity.Post;
import com.qcu.exception.RepeatException;
import com.qcu.service.MinioService;
import com.qcu.service.PostService;
import com.qcu.service.impl.MinioServerImpl;
import com.qcu.util.Response;
import com.qcu.util.ResponseCode;
import com.qcu.util.ThreadLocalUtil;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Name: MyComputer
 * @ClassName UserPostController
 * @Description:
 * @date 2025/2/15 9:29
 */
@RestController
@RequestMapping("/user/post")
public class UserPostController {
    @Resource
    private PostService userPostService;
    @Resource
    private MinioService minioService;
    @Resource
    RedisTemplate redisTemplate;

    /**
     * 创建帖子
     * @param
     * @return null
     */
    @PostMapping(consumes = "multipart/form-data")
    @RequireAuthorization({"USER"})
    public Response save(@RequestPart(required = false) MultipartFile file,@RequestParam String title,@RequestParam String content)throws RepeatException {
        try {
            byte[] bytes = file.getBytes();
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            // 获取文件类型,不要.
            String type = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            // minioService 中完成文件名的MD5处理
            String imgUrl = minioService.upload(originalFilename, bytes,type);
            boolean save = userPostService.savePost(title,content,imgUrl);
            return save ? Response.success(imgUrl) : Response.failure(ResponseCode.FAILURE);

        } catch (IOException e) {
            throw new RepeatException(e.getMessage());
        }

    }

    /**
     * 获取帖子列表
     * @return {title,username,createdAt,good}
     */
    @GetMapping
    @RequireAuthorization({"USER"})
    @LimitRate(key = "getPostList",permitsPerSecond = 2,expire = 10,msg = "八嘎雅鹿，你滴点那么快滴干什么滴干活...")
    public Response list() {
        LambdaQueryWrapper<Post> wrapper = new LambdaQueryWrapper<>();
        // state != 0
        wrapper.ne(Post::getState, 0);
        return Response.success(userPostService.list(wrapper));
    }

    /**
     * 获取帖子详情
     * @param id
     * @return {title,username,createdAt,good,content}
     */
    @GetMapping("/{id}")
    @LimitRate(key = "getPostListById",permitsPerSecond = 2,expire = 10,msg = "八嘎雅鹿，你滴点那么快滴干什么滴干活...")
    @RequireAuthorization({"USER"})
    public Response getById(@PathVariable String id) {
        return Response.success(userPostService.getById(new LambdaQueryWrapper<Post>().eq(Post::getUserId,id).ne(Post::getState,0)));
    }

    /**
     * 点赞
     * @param id
     * @return
     */
    @PutMapping("/{id}/good")
    @RequireAuthorization({"USER"})
    public Response good(@PathVariable String id) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        // 在redis中找到点赞列表
        String goodStr = (String) redisTemplate.opsForValue().get("good");
        // 所有帖子的点赞列表
        Map<String,List<Integer>> good = (Map<String, List<Integer>>) JSON.parse(goodStr);
        // 当前帖子的点赞列表
        if (good == null){
            good = new HashMap<>();
            List<Integer> userL = new ArrayList<Integer>();
            userL.add(userId);
            good.put(id,userL);
            redisTemplate.opsForValue().set("good",JSON.toJSONString(good));
            // 更新数据库
            Post post = userPostService.getById(id);
            post.setGood(post.getGood()+1);
            boolean update = userPostService.updateById(post);
            return update ? Response.success() : Response.failure(ResponseCode.FAILURE);

        }
        List<Integer> userL = good.get(id);
        // redis找不到帖子，则放入并点赞
        if (userL == null){
            userL = new ArrayList<>();
            userL.add(userId);
            good.put(id,userL);
            redisTemplate.opsForValue().set("good",JSON.toJSONString(good));

            // 更新数据库
            Post post = userPostService.getById(id);
            post.setGood(post.getGood()+1);
            boolean update = userPostService.updateById(post);
            return update ? Response.success() : Response.failure(ResponseCode.FAILURE);
        }
        // 用户列表找不到，可以点赞
        if (!userL.contains(userId)){
            // 将当前用户放入redis
            good.get(id).add(userId);
            redisTemplate.opsForValue().set("good",JSON.toJSONString(good));
            // 更新数据库
            Post post = userPostService.getById(id);
            post.setGood(post.getGood()+1);
            boolean update = userPostService.updateById(post);
            return update ? Response.success() : Response.failure(ResponseCode.FAILURE);
        }
        return Response.failure(ResponseCode.FAILURE,"您已经点过赞了");
    }

}
